package multi_thread.advanced;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Cheng Jun
 * Description: 演示 CAS 的 ABA 现象
 * Atomically sets the value to the given updated value if the current value == the expected value.
 * @version 1.0
 * @date 2021/9/24 20:21
 */
public class CAS_ABAExample {

    private static AtomicInteger TICKETS = new AtomicInteger(100);

    public static void main(String[] args) throws InterruptedException {
        // 票数初始值
        int tickets = TICKETS.get();
        Thread thread_0 = new Thread(() -> {
            // 票数从 100 -> 101，再从101-> 100
            TICKETS.compareAndSet(TICKETS.get(), 101);
            TICKETS.compareAndSet(TICKETS.get(), 100);
            System.out.println(Thread.currentThread().getName() + "：当前票数 " + TICKETS.get());
        }, "thread-0");

        Thread thread_1 = new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 如果 TICKETS 的 value 和 tickets的值 一致，就可以set TICKETS的value值为 102
            System.out.println(TICKETS.compareAndSet(tickets, 102));
            System.out.println(Thread.currentThread().getName() + "：当前票数 " + TICKETS.get());
        }, "thread-1");

        thread_0.start();
        Thread.sleep(100);
        thread_1.start();

    }

}
